<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="所属表名" prop="tbName">
          <el-select v-model="queryParams.tbName" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in tbOptions"
              :key="item.id"
              :label="item.tbName"
              :value="item.tbName"
            ></el-option>
          </el-select>
        </el-form-item>
      <el-form-item label="字段名称" prop="prop">
        <el-input
          v-model="queryParams.prop"
          placeholder="请输入字段名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="字段描述" prop="label">
        <el-input
          v-model="queryParams.label"
          placeholder="请输入字段描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:prop:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:prop:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:prop:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:prop:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="propList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="字段名称" align="center" prop="prop" />
      <el-table-column label="所属表名" align="center" prop="tbName" />
      <el-table-column label="字段描述" align="center" prop="label" />
      <el-table-column label="字段类型" align="center" prop="propType" />
      <el-table-column label="状态" prop="status" width="70">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === '0'">正常</el-tag>
          <el-tag type="danger" v-if="scope.row.status === '1'">停用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否基础字段" prop="isCustom" width="115">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isCustom === '0'">动态字段</el-tag>
          <el-tag type="info" v-if="scope.row.isCustom === '1'">案卷表基础字段</el-tag>
          <el-tag type="info" v-if="scope.row.isCustom === '2'">卷内表基础字段</el-tag>
          <el-tag type="info" v-if="scope.row.isCustom === '3'">独立表基础字段</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="是否可见" prop="isCustom" width="80">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isView === '0'">可见</el-tag>
          <el-tag type="warning" v-if="scope.row.isView === '1'">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" min-width="50px"/>
      <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.isCustom === '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:prop:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.isCustom === '0'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:prop:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改动态字段管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属表名" prop="tableId" v-if="isAdd === '0'">
          <el-select v-model="form.tableId" filterable placeholder="请选择">
            <el-option
              v-for="item in tbOptions"
              :key="item.id"
              :label="item.tbName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="字段名称" prop="prop" v-if="isAdd === '0'">
          <el-input v-model="form.prop" placeholder="规则：“a-z”、“A-Z”。遵循驼峰命名法，例如：userName" />
        </el-form-item>
        <el-form-item label="字段描述" prop="label">
          <el-input v-model="form.label" placeholder="请输入字段描述" />
        </el-form-item>
        <el-form-item label="字段类型" prop="propType" v-if="isAdd === '0'">
          <el-select v-model="form.propType" filterable placeholder="请选择">
            <el-option
              v-for="item in prtpOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
         <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否可见">
          <el-radio-group v-model="form.isView">
            <el-radio label="0">可见</el-radio>
            <el-radio label="1">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number v-model="form.orderNum" controls-position="right" :min="10" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listProp,
  getProp,
  addProp,
  updateProp,
  delProp
} from "@/api/tool/prop";
import { listTable } from "@/api/tool/table";

export default {
  name: "Prop",
  data() {
    var validProp = (rule, value, callback) => {
        let reg = /[^a-zA-Z]/g;
        if(reg.test(value)){
          callback(new Error('字段名称规则：“a-z”、“A-Z”。遵循驼峰命名法，比如：userName'));
        } else {
          callback();
        }
    };
    return {
      // 遮罩层
      loading: true,
      // 判断新增删除
      isAdd: '0',
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 树形分类数据
      typeOptions: undefined,
      // 动态表格数据下拉菜单
      tbOptions: undefined,
      // 字段类型
      prtpOptions: [
        { label: "数字：int", value: "int" },
        { label: "字符串：varchar(255)", value: "varchar(255)" },
        { label: "文本：longtext", value: "longtext" },
        { label: "日期：date", value: "date" },
        { label: "时间：datetime", value: "datetime" }
      ],
      // 动态字段管理表格数据
      propList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prop: null,
        label: null,
        createTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        tableId: [
          { required: true, message: "表名称不能为空", trigger: "change" }
        ],
        prop: [
          { required: true, message: "字段名称不能为空", trigger: "blur" },
          { validator: validProp, trigger: 'blur' }
        ],
        label: [
          { required: true, message: "字段描述不能为空", trigger: "blur" }
        ],
        propType: [{ required: true, message: "字段类型不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ]
      },
    };
  },
  created() {
    this.getList();
    this.getTableList();
  },
  methods: {
    /** 获取动态表数据下拉菜单 */
    getTableList() {
      listTable().then(response => {
        this.tbOptions = response.rows;
      });
    },
    /** 查询动态字段管理列表 */
    getList() {
      this.loading = true;
      listProp(this.queryParams).then(response => {
        this.propList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tableId: null,
        prop: null,
        label: null,
        propType: null,
        status: "0",
        isView: "0",
        orderNum: 10,
        isCustom: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isAdd = '0';
      this.reset();
      this.open = true;
      this.title = "添加动态字段管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isAdd = '1';
      this.reset();
      const id = row.id || this.ids;
      getProp(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改动态字段管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateProp(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProp(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function() {
          return delProp(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "tool/prop/export",
        {
          ...this.queryParams
        },
        `prop_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
